'use client';

import { CalendarIcon } from 'lucide-react';
import * as React from 'react';
import type { DateRange } from 'react-day-picker';

import { Button } from '@/components/ui/button';
import { Calendar } from '@/components/ui/calendar';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import { cn } from '@/lib/utils';
import dayjs from 'dayjs';

export default function DateRangePicker({
  onChange,
  value,
}: {
  onChange: (value: DateRange | undefined) => void;
  value: DateRange;
}) {
  return (
    <Popover>
      <PopoverTrigger asChild>
        <div>
          <Button
            id="date"
            type="button"
            variant={'outline'}
            className={cn(
              'w-[300px] justify-start text-left font-normal',
              !value && 'text-muted-foreground',
            )}
          >
            <CalendarIcon />
            {value?.from ? (
              value.to ? (
                `${dayjs(value.from).format('YYYY-MM-DD')} - ${dayjs(value.to).format('YYYY-MM-DD')}`
              ) : (
                dayjs(value.from).format('YYYY-MM-DD')
              )
            ) : (
              <span>Pick a date</span>
            )}
          </Button>
        </div>
      </PopoverTrigger>
      <PopoverContent className="w-auto p-0" align="start">
        <Calendar
          initialFocus
          mode="range"
          defaultMonth={value?.from}
          selected={value}
          onSelect={(data) =>
            data
              ? onChange({
                  from: dayjs(data.from).startOf('day').toDate(),
                  to: data.to
                    ? dayjs(data.to).endOf('day').toDate()
                    : undefined,
                })
              : onChange(undefined)
          }
          numberOfMonths={2}
        />
      </PopoverContent>
    </Popover>
  );
}
